package com.greenet.companytemplate.manager.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Created by Administrator on 2016/1/4.
 */
@Component
public class DirectoryToZip {

    protected Logger logger= LoggerFactory.getLogger(getClass());

    public void toZip(String path, OutputStream outputStream) throws IOException {
        File f=new File(path);
        InputStream inputStream=null;
        ZipOutputStream zipOutputStream=new ZipOutputStream(outputStream);
        try {
            if(f.isDirectory()){
                File[] files=f.listFiles();
                for(File file : files){
                    if(!file.isDirectory()){
                        inputStream=new FileInputStream(file);
                        logger.info("filename={}",file.getName());
                        zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
                        int temp = 0;
                        while ((temp = inputStream.read()) != -1) {
                            zipOutputStream.write(temp);
                        }
                        inputStream.close();
                    }
                }
            }
            zipOutputStream.close();
        } finally {
            if(inputStream!=null)
                inputStream.close();
        }
    }
}
